/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * 知启蒙Servlet兼容库（zhiqim_servlet）在LGPL3.0协议下开源：https://www.zhiqim.com/gitcan/zhiqim/zhiqim_servlet.htm
 *
 * This file is part of [zhiqim_servlet].
 * 
 * [zhiqim_servlet] is free software: you can redistribute
 * it and/or modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * [zhiqim_servlet] is distributed in the hope that it will
 * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with [zhiqim_servlet].
 * If not, see <http://www.gnu.org/licenses/>.
 */
package org.zhiqim.servlet;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.zhiqim.httpd.HttpException;
import org.zhiqim.httpd.context.ServiceExecutor;
import org.zhiqim.httpd.context.ZmlContextConstants;
import org.zhiqim.httpd.context.ZmlExecutor;
import org.zhiqim.kernel.config.Config;
import org.zhiqim.kernel.config.Group;
import org.zhiqim.kernel.util.Strings;
import org.zhiqim.kernel.util.Systems;
import org.zhiqim.kernel.util.Validates;

/**
 * ZhiqimServlet为核心Servlet，负责启动退出、服务检索、服务处理等。
 *
 * 一、启动参数六项：
 * 1、welcomeUrl                     /index.htm          默认首页URL
 * 2、matchType                      exact-prior         路径匹配类型精确优先还是循序exact-prior|in-turn，默认为exact-prior
 * 3、zml.pattern                    *.htm,*.zml         ZML模式，未配置缺省为*.htm,*.zml，可根据自身定制不同的后缀
 * 4、zml.maxKeepTime                86400               ZML模板保持时长，单位：秒，未配置缺省24小时
 * 5、zml.maxIdleTime                3600                ZML模板空闲时长，单位：秒，未配置缺省1小时
 *
 * 二、HttpHandler列表
 * 1、/service/*                     服务处理器
 * 2、/404.404                       未找到处理器
 * 3、/conf/*,/zview/*,/ztmpl/*.htm  过滤
 * 4、/,/*                           ZML处理器
 * 
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class ZhiqimServlet extends HttpServlet implements ZmlContextConstants
{
    private static final long serialVersionUID = 1L;
    private static final String ZC_SERVLET_CONTEXT_HOME_KEY     = "zhiqim.servlet.context.home";
    private static final String ZC_SERVLET_NOT_FOUND_URL        = "/404.404";
    private static final String ZC_SERVLET_ERROR_REQUEST_URI    = "javax.servlet.error.request_uri";
    
    //两项启动退出，分别负责配置别名服务和上下文环境
    private ZhiqimController controller;
    private ZmlContext context;
    
    //两项服务处理，分别为/service/*和{/,/404.404,*.html}
    private ZmlExecutor zExecutor;
    private ServiceExecutor sExecutor;
    
    /************************************************************************/
    //初始化和销毁
    /************************************************************************/

    /** 初始化 */
    public void init() throws ServletException
    {
        //1.设置${zhiqim.servlet.context.home}系统属性
        ServletContext servletContext = getServletContext();
        Systems.setProperty(ZC_SERVLET_CONTEXT_HOME_KEY, servletContext.getRealPath(""));
        
        //2.把上下文环境参数放置到属性中
        Enumeration<String> svcEnums = servletContext.getInitParameterNames();
        while (svcEnums.hasMoreElements())
        {
            String key = svcEnums.nextElement();
            servletContext.setAttribute(key, servletContext.getInitParameter(key));
        }
        
        Enumeration<String> enums = getInitParameterNames();
        while (enums.hasMoreElements())
        {
            String key = enums.nextElement();
            servletContext.setAttribute(key, getInitParameter(key));
        }
        
        //3.初始化配置、别名和服务控制器
        controller = new ZhiqimController(servletContext);
        controller.startup();
        
        //4.新建ZmlExecutor&ServiceExecutor
        String patternUrl = getInitParameter(_ZML_PATTERN_, _ZML_PATTERN_DEFAULT_);
        zExecutor = new ZmlExecutor(patternUrl);
        sExecutor = new ServiceExecutor();
        
        //5.新建ZmlServletContext并放置到上下文环境中，再初始化
        context = new ZmlContext(servletContext, zExecutor, sExecutor);
        context.create(new Group(new Config("上下文配置", "zhiqim.xml"), "servlet", "上下文配置"));
    }
    
    /** 销毁 */
    public void destroy()
    {
        if (context != null)
            context.destroy();
        
        if (controller != null)
            controller.shutdown();
    }
    
    /************************************************************************/
    //doHead & doGet & doPost
    /************************************************************************/
    
    protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        handle(request, response);
    }
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        handle(request, response);
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        handle(request, response);
    }
    
    private void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        ZmlResponse resp = new ZmlResponse(response);
        ZmlRequest req = new ZmlRequest(request, resp);
        
        String path = req.getPathInContext();
        if (path.startsWith(_PATH_SERVICE_PREFIX_))
        {//服务处理器
            sExecutor.handle(req, resp);
        }
        else if (ZC_SERVLET_NOT_FOUND_URL.equals(path))
        {//处理servlet未找到
            handleNotFound(req, resp);
        }
        else if (context.isFilterPath(path))
        {//过滤
            handleFilter(req, resp);
        }
        else
        {//缺省ZML处理器
            if ("/".equals(path) && Validates.isNotEmpty(context.getWelcomeUrl()))
                req.setPathInContext(context.getWelcomeUrl());
    
            zExecutor.handle(req, resp);
        }
    }
    
    /** 未找到再从组件中找一次，再没找到才404 */
    private void handleNotFound(ZmlRequest request, ZmlResponse response) throws HttpException, IOException
    {
        ZmlContext context = request.getContext();
        
        //先置为成功，并读取原错误的URL放置回请求中
        Object path = request.getAttribute(ZC_SERVLET_ERROR_REQUEST_URI);
        if (path == null)
        {//没有请求地址则可能是访问到/404.404
            context.getNotFoundHandler().handle(request, response);
        }
        else
        {//有请求地址在Servlet容器中未找到，重置成功，到组件中查找
            response.sendHeader(_200_OK_);
            request.setPathInContext(Strings.valueOf(path));
            context.handleComponentResource(request, response);
        }
    }
    
    /** 处理过滤 */
    private void handleFilter(ZmlRequest request, ZmlResponse response) throws IOException, ServletException
    {
        response.sendError(_403_FORBIDDEN_);
    }
    
    /************************************************************************/
    //工具方法
    /************************************************************************/
    
    private String getInitParameter(String key, String defaultValue)
    {
        String value = getInitParameter(key);
        return Validates.isEmptyBlank(value)?defaultValue:value;
    }
}
